#include "MyWebInteractive.h"
#include "CccWebEngineView.h"
#include <QThread>
#include <QUuid>
#include <QDebug>

MyWebInteractive::MyWebInteractive(QWidget* parent)
	: QWidget(parent)
	, ui(new Ui::MyWebInteractiveClass())
{
	ui->setupUi(this);

}

MyWebInteractive::~MyWebInteractive()
{
	delete ui;
}

void MyWebInteractive::addLoop(const QString& uuid, QEventLoop* pLoop)
{
	m_loop_map[uuid] = pLoop;
	pLoop->setProperty("uuid", uuid);
	connect(this, &MyWebInteractive::signalRunJsOver, [&](const QString& uuid) {
		m_loop_map[uuid]->quit();
		removeLoop(uuid);
	});
}

void MyWebInteractive::removeLoop(const QString& uuid)
{
	auto iter = m_loop_map.find(uuid);
	if (iter != m_loop_map.end()) {

		QEventLoop* pLoop =  m_loop_map[uuid];
		m_loop_map.erase(iter);
		delete pLoop;
		pLoop = nullptr;
	}
}

void MyWebInteractive::on_callJSBtn_clicked()
{
	qDebug() << "start";
	QSharedPointer<QEventLoop> loop = QSharedPointer<QEventLoop>(new QEventLoop());
	QString retStr;
	CccWebEngineView::instance()->page()->runJavaScript("add(1,2)",
		[&](const QVariant& v)
		{
			retStr = v.toString();
			qDebug() << "ret:" << retStr;
			if (loop->isRunning()) {
				loop->quit();
			}
		});
	loop->exec(QEventLoop::AllEvents | QEventLoop::WaitForMoreEvents);
	qDebug() << "end";
}
